﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace DataBaseLibrary
{
    public static class CryptoClass
    {
        public static string Encrypt(string originalString, String key)
        {
            byte[] keyBytes = ASCIIEncoding.ASCII.GetBytes(key);
            if (String.IsNullOrEmpty(originalString))
            {
                return String.Empty;
            }
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream,  cryptoProvider.CreateEncryptor(keyBytes, keyBytes), CryptoStreamMode.Write);
            StreamWriter writer = new StreamWriter(cryptoStream);
            writer.Write(originalString);
            writer.Flush();
            cryptoStream.FlushFinalBlock();
            writer.Flush();
            return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        }


        public static string Decrypt(string cryptedString, String key)
        {
            byte[] keyBytes = ASCIIEncoding.ASCII.GetBytes(key);
            if (String.IsNullOrEmpty(cryptedString))
            {
                return String.Empty;
            }
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream memoryStream = new MemoryStream
                    (Convert.FromBase64String(cryptedString));
            CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(keyBytes, keyBytes), CryptoStreamMode.Read);
            StreamReader reader = new StreamReader(cryptoStream);
            return reader.ReadToEnd();
        }
    }

}
